package com.example.taxfloatproject20240926.ui.socket;

import android.util.Log;

import com.example.taxfloatproject20240926.ui.utils.Constant;
import com.example.taxfloatproject20240926.ui.busevent.BusProvider;
import com.example.taxfloatproject20240926.ui.event.ConnEvent;
import com.example.taxfloatproject20240926.ui.event.MsgEvent;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

@ChannelHandler.Sharable
public class HeartNettyClientHandler extends ChannelInboundHandlerAdapter {
    private RetryStrategy retryStrategy;

    /**
     * 空闲次数
     */
    private int idle_count = 1;

    /**
     * 循环发送心跳次数
     */
    private int fcount = 1;
    /**
     * 接收消息次数
     */
    private int count = 1;

    public HeartNettyClientHandler(RetryStrategy retryStrategy) {
        this.retryStrategy = retryStrategy;
    }


    /**
     * 建立连接时
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Log.i(CmdUtils.TAG,"建立连接时：" + date());
        BusProvider.getInstance().post(new ConnEvent(true));
        ctx.fireChannelActive();
        String msg =" /cmd init /devid " + Constant.eval_addr + "/End";
        ctx.write(Unpooled.copiedBuffer(msg, Charset.forName("GBK")));
        ctx.flush();
    }


     @Override
     public void channelInactive(ChannelHandlerContext ctx) throws Exception {
         Log.i(CmdUtils.TAG,"NettyRetryClientHandle===触发通道不活跃, 进行重连!");
         BusProvider.getInstance().post(new ConnEvent(false));
         retryStrategy.setConsumer(el->{
             Log.i(CmdUtils.TAG,"NettyRetryClientHandle===重连成功,  触发做自己的事情!!!!!!!");
             BusProvider.getInstance().post(new ConnEvent(true));
         });
         retryStrategy.processRetryConnect(ctx);
     }


    /**
     * 心跳请求处理，每4秒发送一次心跳请求;
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {
        Log.i(CmdUtils.TAG,"循环发送心跳的时间：" + date() + "，次数" + fcount);
        if (obj instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) obj;
            if (IdleState.WRITER_IDLE.equals(event.state())) { // 如果写通道处于空闲状态就发送心跳命令
                String heartMsg = "/cmd heartbeat/devid " + Constant.eval_addr + "/End";
                ctx.channel().writeAndFlush(heartMsg);
                Log.i(CmdUtils.TAG, "心跳包发送次数：" + idle_count);
                idle_count++;
            }
        }

        fcount++;
    }

    /**
     * 业务逻辑处理
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            String msgResult = (String) msg;
            Log.i(CmdUtils.TAG, "第" + count + "次" + "，客户端收到的消息:" + msg + ",result is " + msgResult);
            if (!"123".equals(msgResult)) {
                BusProvider.getInstance().post(new MsgEvent(msgResult));
                String evalMsg = "/cmd  help /devid " + Constant.eval_addr + "/End";
                ctx.write(Unpooled.copiedBuffer(evalMsg,
                        Charset.forName("GBK")));
                ctx.flush();
            }
        } catch (Exception e) {
            Log.e(CmdUtils.TAG, " channelRead e " + e.getMessage());

        }
        count++;
    }

    private String date() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }
}



